package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("setmeal")
@Slf4j
public class SetmealController {


    @DubboReference
    private SetmealService setmealService;

    @Autowired
    private QiniuUtils qiniuUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * @Author: JASON 
     * @Date: 9:08 2021/1/6
     * @Parms [queryPageBean]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 套餐管理分页查询
    */
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean){
        log.info("Controller套餐管理分页查询"+queryPageBean);
        PageResult pageResult = setmealService.findPage(queryPageBean);
        return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, pageResult);
    }

    /**
     * @Author: JASON
     * @Date: 17:27 2021/1/9
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 查询所有
    */
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @GetMapping("findAll")
    public Result findAll(){
        log.info("套餐查询所有");
        List<Setmeal> list=setmealService.findAll();
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, list);
    }


    /**
     * @Author: JASON
     * @Date: 9:38 2021/1/6
     * @Parms [setmeal, checkgroupIds]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 套餐管理新增
    */
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    @PostMapping("add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        log.info("Controller套餐管理"+setmeal+"检查组id"+checkgroupIds);
        //特殊处理img属性 去掉七牛云地址 只保留原来名字
        if(!StringUtils.isEmpty(setmeal.getImg())){
            String img = setmeal.getImg().replace(qiniuUtils.getUrlPrefix(), "");
            setmeal.setImg(img);
        }
        setmealService.add(setmeal, checkgroupIds);
        //从redis中清除记录图片
        redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(setmeal.getImg());

        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }


    /**
     * @Author: JASON
     * @Date: 10:08 2021/1/6
     * @Parms [id]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 根据id查询套餐
    */
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @GetMapping("findById")
    public Result findById(Integer id){
        log.info("Controller套餐根据id查询"+id);
        Setmeal setmeal=setmealService.findById(id);
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
    }

    /**
     * @Author: JASON
     * @Date: 10:19 2021/1/6
     * @Parms [id]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 根据SetmealId查询CheckGroupIds
    */
    @GetMapping("findCheckGroupIdsBySetmealId")
    public Result findCheckGroupIdsBySetmealId(Integer id){
        log.info("Controller根据SetmealId查询CheckGroupIds"+id);
        List<Integer> list = setmealService.findCheckGroupIdsBySetmealId(id);
        return new Result(true, "根据SetmealId查询CheckGroupIds成功",list);
    }


    /**
     * @Author: JASON
     * @Date: 11:43 2021/1/6
     * @Parms [multipartFile]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 新增套餐文件上传
     * @RequestParam :指定前端上传的文件名一致
    */
    @PostMapping("upload")
    public Result upload(@RequestParam("imgFile")MultipartFile multipartFile){
        try {
            log.info("文件上传，name:{},size:{}", multipartFile.getOriginalFilename(), multipartFile.getSize());
            //原始文件名
            String originalFileName = multipartFile.getOriginalFilename();
            //使用UUID构造不重复的文件名 并加上原始的文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + originalFileName;
            //优化定时任务定时清除图片 拼接时间戳
            fileName = System.currentTimeMillis() + "_" + fileName;
            log.info("拼接时间戳后的图片名"+fileName);
            //写入redis中
            redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).add(fileName);
            //获取输入流并上传
            InputStream is = multipartFile.getInputStream();
            qiniuUtils.upload2Qiniu(is, fileName);

            //构造返回值   qiniuUtils.getUrlPrefix() 返回的是七牛云存储的地址（图片的唯一标识）网络路径
            String pic = qiniuUtils.getUrlPrefix() + fileName;
            return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, pic);
        } catch (IOException e) {
            log.error("[新增套餐-上传图片失败]", e.getMessage());
            return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }
    }
}
